package com.community.process._1010.consumer;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.community.process._1010.common.utils.RedisConstant;
import com.community.process._1010.common.utils.redis.RedisUtil;
import com.community.process._1010.config.ProcessOrderNotificationQueueConfig;
import com.community.process._1010.consumer.service.ConsumerHandleService;
import com.community.process._1010.domains.external.ExternalOrderInfo;
import com.rabbitmq.client.Channel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @Description:
 * @Author: Administrator to Zbs
 * @Date: 2024/7/19 星期五 18:03
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class ProcessOrderNotificationQueueConsumer {

    private final ConsumerHandleService consumerHandleService;

    @RabbitListener(queues = ProcessOrderNotificationQueueConfig.QUEUE_NAME)
    public void receiveDirectQueue(String msg, Channel channel, Message message) throws IOException {
        log.info("到餐加工-订单主题队列接收消息：{},{}", msg,new String(message.getBody(), StandardCharsets.UTF_8));
        String originMessageBody = new String(message.getBody(), StandardCharsets.UTF_8);
        int indexOf = originMessageBody.indexOf("{");
        if (indexOf != -1) {
            String substring = originMessageBody.substring(indexOf);
            JSONObject jsonObject = JSON.parseObject(substring);
            // 删除支付信息payInfo ，这个转json有问题
            jsonObject.remove("payInfo");
            ExternalOrderInfo externalOrderInfo = jsonObject.toJavaObject(ExternalOrderInfo.class);
            if (!externalOrderInfo.getBusinessType().equals(8)) {
                return;
            }
            consumerHandleService.handlePayReturnMessage(externalOrderInfo);
            RedisUtil.del(RedisConstant.getProcessOrderRedisKey(externalOrderInfo.getOrderNo()));
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
